package com.tanglongan.designPattern.dp03_prototype.demo01;

import com.google.common.collect.Lists;
import lombok.Data;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class JavaCloneableDemo03 {


    public static void main(String[] args) throws IOException {
        List<String> hobbies = Lists.newArrayList("书法", "美术", "羽毛球");

        ConcretePrototype prototype = new ConcretePrototype();
        prototype.setAge(18);
        prototype.setName("Tomcat");
        prototype.setHobbies(hobbies);
        System.out.println(prototype);


        ConcretePrototype clone = prototype.deepClone();
        clone.getHobbies().add("围棋");

        System.out.println(prototype);
        System.out.println(clone);
    }

    @Data
    static class ConcretePrototype implements Cloneable, Serializable {
        private int age;
        private String name;
        private List<String> hobbies;

        @Override
        protected ConcretePrototype clone() {
            try {
                ConcretePrototype prototype = (ConcretePrototype) super.clone();
                prototype.setHobbies((List)((ArrayList)prototype.hobbies).clone());
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return null;
        }

        public ConcretePrototype deepClone() throws IOException {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(this);

                ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(bis);
                return (ConcretePrototype) ois.readObject();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}
